package system.communication;

import system.track.Sensor;
/**
 * This is a simple Threaded class which checks if the Monitor has sensor Messages,
 * and if it does it notifies the respective registered sensor(s) of the tripped status.
 * 
 * @author Elliot Cash
 * @version Cycle 1 - complete
 */
public class SensorNotifier extends Thread
{
    /**
     * Constructor for Objects of class SensorNotifier.
     */
    public SensorNotifier()
    {
    }

    /**
     * Starts the SensorNotifier thread to check if there are any Sensor Messages in
     * the ConcreteMonitor, if there are it compares the Sensor Messages values, which
     * are the id's of sensors, to the Registered sensors in the ConcreteMonitor. If the ids,
     * match then the sensor registered to the monitor has its tripped method called.
     */
    @Override
    public void run()
    {
        System.out.println("Running a Sensor Notifier."); //debugging line
        
        //while the Monitor holds a Sensor Message
        while(ConcreteMonitor.getInstance().hasSensorMessage())
        {
            Message topMessage = ConcreteMonitor.getInstance().getSensorMessage();
            if(topMessage.getArg(MessageArg.SENSOR_VALUE_TWO) == null)
            {
                //if there is only one Sensor in the Message, trip it
                for(Sensor s : ConcreteMonitor.getInstance().sensors)
                {
                    if(s.getID() == Integer.parseInt(topMessage.getArg(MessageArg.SENSOR_VALUE_ONE)))
                    {
                        System.out.println("tripping a sensor");
                        s.tripped();
                    }    
                }
            }
            else
            {
                //trip both Sensors in the message
                for(Sensor s : ConcreteMonitor.getInstance().sensors)
                {
                    if(s.getID() == Integer.parseInt(topMessage.getArg(MessageArg.SENSOR_VALUE_ONE)))
                    {
                        s.tripped();
                    }
                    else if(s.getID() == Integer.parseInt(topMessage.getArg(MessageArg.SENSOR_VALUE_TWO)))
                    {
                        s.tripped();
                    }
                }
            }
            /*try
            {
                Thread.sleep(1);
            }
            catch (InterruptedException ex)
            {
                System.err.println(ex.getMessage());
            }*/
        }
    }

    /**
     * Ends the thread.
     */
    public void end()
    {

    }
}
